package org.ims.inv.web.action.card;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ims.inv.model.card.ModelPersonalCard;
import org.ims.inv.model.system.ModelAppDictionary;
import org.ims.inv.model.system.ModelAppUser;
import org.ims.inv.service.card.ServicePersonalCard;
import org.ims.inv.web.util.ContextUtil;
import org.ims.inv.web.util.ExcelTemplateSupport;
import org.springframework.beans.BeanUtils;

import cn.trymore.core.util.UtilCollection;
import cn.trymore.core.util.UtilDate;
import cn.trymore.core.util.UtilString;
import cn.trymore.core.util.excel.AbstractExcelParser;
import cn.trymore.core.util.excel.ExcelRowData;
import cn.trymore.core.util.excel.PoiExcelParser;
import cn.trymore.core.vo.VoTplExcelObj;
import cn.trymore.core.web.paging.PaginationSupport;
import cn.trymore.core.web.paging.PagingBean;

/**
 * Action: 个人名录
 * 
 * @author Jeccy.Zhao
 *
 */
public class CardPersonalAction
extends CardBaseAction
{
	/**
	 * The LOGGER
	 */
	private static final Logger LOGGER = Logger.getLogger(CardPersonalAction.class);
	
	/**
	 * The service of personal card
	 */
	private ServicePersonalCard servicePersonalCard;
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 个人名片首页
	 */
	public ActionForward pagePersonalCardIndex (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			ModelPersonalCard formEntity = (ModelPersonalCard) form;
			
			String industryId = request.getParameter("industryId");
			if (UtilString.isNotEmpty(industryId))
			{
				ModelAppDictionary dict = new ModelAppDictionary();
				dict.setId(industryId);
				formEntity.setIndustry(dict);
			}
			
			PagingBean pagingBean = this.getPagingBean(request);
			PaginationSupport<ModelPersonalCard> pagingData = this.servicePersonalCard.getPagination(formEntity, pagingBean);
			
			// 查询行业字典
			request.setAttribute("industry", this.getDictionariesByType("DICT_CARD_INDUSTRY"));
			request.setAttribute("datagrid", pagingData);
			
			this.outWritePagination(request, pagingBean, pagingData);
			this.outWriteAllParameters(request);
			return mapping.findForward("page.card.personal.index");
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 保存个人名片
	 */
	public ActionForward actionSavePersonalCard (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			ModelPersonalCard formEntity = (ModelPersonalCard) form;
			ModelPersonalCard entity = null;
			
			boolean isEdit = this.isObjectIdValid(request.getParameter("id"));
			if (isEdit)
			{
				entity = this.servicePersonalCard.get(request.getParameter("id"));
				BeanUtils.copyProperties(formEntity, entity, new String[] {"industry", "recorder", "creationTime"});
			}
			else
			{
				entity = formEntity;
				entity.setCreationTime(new Date());
			}
			
			// 行业
			String industryId = request.getParameter("industryId");
			if (UtilString.isNotEmpty(industryId))
			{
				entity.setIndustry(this.serviceAppDictionary.get(industryId));
			}
			else
			{
				entity.setIndustry(null);
			}
			
			// 所属项目编号
			entity.setProjectNo(request.getParameter("pobj.projectNo"));
			
			// 登记人
			String recorderId = request.getParameter("rec.id");
			if (UtilString.isNotEmpty(recorderId))
			{
				ModelAppUser referral = this.serviceAppUser.get(recorderId);
				if (referral != null)
				{
					entity.setRecorder(referral);
					entity.setRecorderName(referral.getUsername());
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("登记人不存在:" + recorderId));
				}
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("登记人不能为空.."));
			}
			
			entity.setLastModifiedTime(new Date());
			
			this.servicePersonalCard.save(entity);
			
			// 保存成功后, Dialog进行关闭
			return ajaxPrint(response, 
					getSuccessCallback("名片保存成功.", CALLBACK_TYPE_CLOSE, CURRENT_NAVTABID, null, false));
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 删除个人名片
	 */
	public ActionForward actionRemovePersonalCard (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String id = request.getParameter("id");
			if (UtilString.isNotEmpty(id))
			{
				if (this.isObjectIdValid(id))
				{
					ModelPersonalCard entity = this.servicePersonalCard.get(id);
					if (entity == null)
					{
						return ajaxPrint(response, getErrorCallback("名片数据不存在, ID:" + id));
					}
					
					this.servicePersonalCard.remove(entity);
					
					// 保存成功后, Dialog进行关闭
					return ajaxPrint(response, 
							getSuccessCallback("名片删除成功.", CALLBACK_TYPE_CLOSE, CURRENT_NAVTABID, null, false));
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("非法的名片数据ID:" + id));
				}
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("名片数据ID不能为空."));
			}
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 个人名片弹框页面
	 */
	public ActionForward dialogPersonalCard (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String id = request.getParameter("id");
			if (UtilString.isNotEmpty(id))
			{
				if (this.isObjectIdValid(id))
				{
					ModelPersonalCard entity = this.servicePersonalCard.get(id);
					if (entity == null)
					{
						return ajaxPrint(response, getErrorCallback("名片数据不存在, ID:" + id));
					}
					
					request.setAttribute("entity", entity);
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("非法的名片数据ID:" + id));
				}
			}
			else
			{
				request.setAttribute("recorder", ContextUtil.getCurrentUser());
			}
			
			// 查询行业字典
			request.setAttribute("industry", this.getDictionariesByType("DICT_CARD_INDUSTRY"));
			
			this.outWriteAllParameters(request);
						
			return mapping.findForward("dialog.card.personal.page");
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 个人名录导入页面
	 */
	public ActionForward dialogPersonalCardImportPage (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		return mapping.findForward("dialog.card.personal.import.page");
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 个人名录导出
	 */
	public ActionForward actionExportPersonalCard (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			initFolders();
			
			ModelPersonalCard formEntity = (ModelPersonalCard) form;
			
			// 行业
			String industryId = request.getParameter("industryId");
			if (UtilString.isNotEmpty(industryId))
			{
				formEntity.setIndustry(this.serviceAppDictionary.get(industryId));
			}
			else
			{
				formEntity.setIndustry(null);
			}
			
			PagingBean pagingBean = new PagingBean(1, 0);
			PaginationSupport<ModelPersonalCard> pagingData = 
				this.servicePersonalCard.getPagination(formEntity, pagingBean);
			
			if (pagingData != null && pagingData.getItemCount() > 0)
			{
				VoTplExcelObj obj = ExcelTemplateSupport.getTplObjFromTplFile(
						ExcelTemplateSupport.XLS_TPL_PATH + "/excel.card.personal.xml", null);
				
				if (obj != null)
				{
					List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();
					for (ModelPersonalCard entity : pagingData.getItems())
					{
						Map<String, Object> singleRow = new HashMap<String, Object>();
						singleRow.put("card", entity);
						data.add(singleRow);
					}
					
					obj = ExcelTemplateSupport.fillTplData(obj, data, null);
					obj.setSheetName("个人名录");
					
					String fileName = "exportPersonalCard_" + UtilDate.parseTime(new Date(), "yyyyMMddHHmmssSS") + ".xls";
					ExcelTemplateSupport.createExcel(this.tempPath + "/" + fileName, obj);
					
					return ajaxPrint(response, "{status:200, file:'" + "temp/" + fileName + "', name:'" + fileName + "'}");
				}
				else
				{
					return ajaxPrint(response, "{status:500, message:'文件导出失败.'}");
				}
			}
			else
			{
				return ajaxPrint(response, "{status:500, message:'没有可导出的数据.'}");
			}
			
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, "{status:500, message:'文件导出失败.'}");
		}
	}
	
	/**
	 * 转换excel中的行数据为实体
	 * - 0,   1,    2,   3,   4,   5,  6,   7,          8,          9, 10,  11,  12,  13, 14,  15,  16,  17,     18,  19,  20,     21,      22,     23,      24,  25, 26,  27,  28
	 * - 姓名,英文名,手机,手机,电话,电话,电话,电子邮件地址,电子邮件地址,IM,学校,生日,附注,职位,职位,职位,职位	,所属行业,公司,公司,所属部门,所属部门,关联公司,关联公司,地址,地址,网址,传真,分组
	 * @param rawData
	 * @return
	 * @throws Exception
	 */
	private ModelPersonalCard convertFromRawData (final ExcelRowData rawData)
	{
		ModelPersonalCard entity = null;
		
		if (rawData != null)
		{
			String fullName = this.getCellDataByIndexFromRow(rawData, 0);
			if (!UtilString.isNotEmpty(fullName))
			{
				return entity;
			}
			
			entity = new ModelPersonalCard();
			entity.setFullName(fullName);
			entity.setCompany(this.getCellDataByIndexFromRow(rawData, 18));
			entity.setJobTitle(this.getCellDataByIndexFromRow(rawData, 13));
			entity.setOfficePhone(this.getCellDataByIndexFromRow(rawData, 4));
			entity.setMobilePhone(this.getCellDataByIndexFromRow(rawData, 2));
			entity.setEmail(this.getCellDataByIndexFromRow(rawData, 7));
			entity.setAddress(this.getCellDataByIndexFromRow(rawData, 24));
			entity.setQq(this.getCellDataByIndexFromRow(rawData, 9));
			String industryName = this.getCellDataByIndexFromRow(rawData, 17);
			try
			{
				if (UtilString.isNotEmpty(industryName))
				{
					entity.setIndustry(
							this.serviceAppDictionary.getByTypeAndKey("DICT_CARD_INDUSTRY", industryName));
				}
			}
			catch (Exception e)
			{
				LOGGER.error("Dictionary data does not exist by 'DICT_CARD_INDUSTRY'-: " + industryName);
				entity.setIndustry(null);
			}
			
			entity.setProjectNo(this.getCellDataByIndexFromRow(rawData, 9));
			entity.setRecorderName(this.getCellDataByIndexFromRow(rawData, 10));
			
			try
			{
				ModelAppUser recorder = this.serviceAppUser.findByUserName(entity.getRecorderName());
				if (recorder != null)
				{
					entity.setRecorder(recorder);
				}
			}
			catch (Exception e)
			{
				LOGGER.error(e);
				entity.setRecorder(null);
			}
		}
		
		return entity;
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 个人名录导入
	 */
	public ActionForward actionImportPersonalCard (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String mode = request.getParameter("mode");
			String fileUrls = request.getParameter("fileUrls");
			if (UtilString.isNotEmpty(fileUrls))
			{
				String uploadPath = request.getSession().getServletContext().getRealPath("/uploads/");
				AbstractExcelParser excelParser = new PoiExcelParser(uploadPath + "/" + fileUrls);
				List<ExcelRowData> excelRowData = excelParser.getRowData(0);
				
				if (excelRowData == null)
				{
					return ajaxPrint(response, getErrorCallback("模板数据解析错误..."));
				}
				
				if (excelRowData.size() < 2)
				{
					return ajaxPrint(response, getErrorCallback("导入模板格式不正确, 请重新检查..."));
				}
				
				for(int i = 1; i < excelRowData.size();i++)
				{
					ExcelRowData rawData = excelRowData.get(i);
					ModelPersonalCard formEntity = this.convertFromRawData(rawData);
					if (formEntity != null)
					{
						Date nowDate = new Date();
						formEntity.setCreationTime(nowDate);
						formEntity.setLastModifiedTime(nowDate);
						formEntity.setRecorder(ContextUtil.getCurrentUser());
						formEntity.setRecorderName(ContextUtil.getCurrentUser().getUsername());
						
						boolean overWritten = false;
						
						if (MODE_OVERWRITE.equals(mode))
						{
							// 查找是否已存在同名数据
							List<ModelPersonalCard> cardsByName = 
								this.servicePersonalCard.findCardByNameAndMobile(formEntity.getFullName(), formEntity.getMobilePhone());
							
							if (UtilCollection.isNotEmpty(cardsByName))
							{
								for (ModelPersonalCard card : cardsByName)
								{
									BeanUtils.copyProperties(formEntity, card, new String[] {"id", "industry", "recorder", "creationTime"});
									
									card.setIndustry(formEntity.getIndustry());
									card.setRecorder(formEntity.getRecorder());
									card.setRecorderName(formEntity.getRecorderName());
									card.setLastModifiedTime(new Date());
									
									this.servicePersonalCard.save(card);
									
									overWritten = true;
								}
							}
						}
						else if (MODE_CANCEL.equals(mode))
						{
							// 取消
							continue;
						}
						
						if (!overWritten)
						{
							this.servicePersonalCard.save(formEntity);
						}
					}
				}
				
				return ajaxPrint(response, 
						getSuccessCallback("个人导入成功.", CALLBACK_TYPE_CLOSE, CURRENT_NAVTABID, null, false));				
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("需要先上传文件才能导入数据..."));
			}
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	public static Logger getLogger()
	{
		return LOGGER;
	}

	public ServicePersonalCard getServicePersonalCard()
	{
		return servicePersonalCard;
	}

	public void setServicePersonalCard(ServicePersonalCard servicePersonalCard)
	{
		this.servicePersonalCard = servicePersonalCard;
	}
}
